<template>
  <div class="app-container">
    <div class="search-container">
      <el-form :model="searchParam" :inline="true" label-width="35">
        <el-form-item label="产品">
          <el-input
            v-model="searchParam.materialCode"
            placeholder="请输入产品"
            clearable
            @keyup.enter="search"
            readonly
            @click="showWorkOrderSelect"
          >
            <template #append>
              <el-button @click="resetMaterial">清除</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="年月">
          <!--          <el-input-->
          <!--            v-model="searchParam.yearMonthInventory"-->
          <!--            placeholder="请输入年月;yyyy-mm"-->
          <!--            clearable-->
          <!--            @keyup.enter="search"-->
          <!--          />-->
          <el-date-picker
            v-model="searchParam.yearMonthInventory"
            type="month"
            placeholder="请输入年月"
            value-format="YYYY-MM"
            @keyup.enter="search"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="reset">
            <i-ep-refresh />
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <!--<el-button type="success" plain @click="openDialog()">
          <i-ep-plus/>
          新增
        </el-button>-->
        <el-button type="primary" @click="inventoryImport">导入 </el-button>
        <el-button
          class="ml-3"
          @click="
            useDownload(
              '/mes/mesinitialinventorymaintenance/export',
              '期初库存',
              searchParam
            )
          "
        >
          <template #icon>
            <i-ep-download />
          </template>
          导出
        </el-button>
        <el-button
          @click="
            useDownload(
              '/mes/mesinitialinventorymaintenance/exportTemp',
              '期初库存上传模板',
              searchParam
            )
          "
        >
          导入模板下载
        </el-button>
        <!--<el-button type="success"
                   @click="excelBoxOpen">导入
        </el-button>-->
        <el-dialog title="期初库存数据导入" v-model="excelBox" width="555px">
          <div>
            <el-button
              @click="
                useDownload(
                  '/mes/mesinitialinventorymaintenance/exportTemp',
                  '期初库存上传模板',
                  searchParam
                )
              "
            >
              <template #icon>
                <i-ep-download />
              </template>
              期初库存上传模板下载
            </el-button>
          </div>
          <div style="margin-top: 10px">
            <input
              class="crop-input"
              type="file"
              name="image"
              accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
              ref="onload_exl"
              @change="getfilepath"
            />
            <el-button
              @click="upload"
              :disabled="uploadBtn"
              style="cursor: pointer"
              >上传</el-button
            >
          </div>
        </el-dialog>
      </template>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="tableData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column label="序号" type="index" width="55" align="center" />
        <el-table-column
          label="物料编号"
          prop="materialCode"
          min-width="120"
          show-overflow-tooltip
        />
        <el-table-column
          label="产品"
          prop="materialName"
          min-width="120"
          show-overflow-tooltip
        >
          <template #default="scope">
            {{ scope.row.materialName }}
          </template>
        </el-table-column>
        <el-table-column
          label="年月"
          prop="yearMonthInventory"
          min-width="100"
          show-overflow-tooltip
          align="center"
        />
        <el-table-column
          label="数量"
          prop="quantity"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <el-table-column
          label="单重"
          prop="singleWeight"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <el-table-column
          label="吨位"
          prop="tonnage"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <el-table-column
          label="上月废品率"
          prop="lastMonthScrapRate"
          min-width="100"
          show-overflow-tooltip
          header-align="center"
          align="right"
        />
        <!--<el-table-column label="备注" prop="remarks" min-width="100" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" min-width="100" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="创建人名" prop="createdUserName" min-width="100" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="更新时间" prop="lastUpdateTime" min-width="100" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="更新人名" prop="lastUpdatedUserName" min-width="100" show-overflow-tooltip>
        </el-table-column>-->
        <el-table-column fixed="right" label="操作" width="160" align="center">
          <template #default="scope">
            <!--<el-button
              type="primary"
              size="small"
              link
              @click="openDialogdetail(scope.row)"
            >
              <i-ep-search/>
              查看
            </el-button>-->
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialog(scope.row)"
            >
              <i-ep-edit />
              编辑
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              @click="deleteItem(scope.row.id)"
            >
              <i-ep-delete />
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        :background="true"
        :current-page="pageable.pageNum"
        :page-size="pageable.pageSize"
        :page-sizes="[10, 25, 50, 100]"
        :total="pageable.total"
        layout="total, sizes, prev, pager, next, jumper"
        class="mt-[20px]"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <mesinitialinventorymaintenance-edit
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      @reset-table="(id:string) => (id?.length ? getTableList() : reset())"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
    <!-- 导入货位 -->
    <ImportExcel ref="inventoryImportRef" />

    <!--物料选择-->
    <conten-select
      :visible="selectDialogSELECT.visible"
      @change-visible="changeVisibleSELECT"
      :plantId="searchParam.plantId"
      :brekList="brekList"
    />
  </div>
</template>

<script setup lang="ts">
import { useTable, useDownload, useDictionary } from "@/utils/useTable";
import request from "@/utils/request";

defineOptions({
  name: "MESMESINITIALINVENTORYMAINTENANCE",
  inheritAttrs: false,
});

// 请求参数
const requestApi = "/mes/mesinitialinventorymaintenance/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  materialCode: "",
  yearMonthInventory: "",
  deleted: 0,
};

const deleteParam = {
  api: "/mes/mesinitialinventorymaintenance/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  ids,
  getTableList,
  search,
  reset,
  handleSizeChange,
  handleCurrentChange,
  handleSelectionChange,
  handleTableDelete,
  loading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

onMounted(() => {
  getTableList();
});

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/mes/mesinitialinventorymaintenance/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开期初库存表单弹窗 */
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改期初库存";
    getInfo(roleObj.id);
  } else {
    addDialog.title = "新增期初库存";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}

/** 打开期初库存表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  addDialog.title = "期初库存详情";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}

// 导入excel
const uploadApi = "/mes/mesinitialinventorymaintenance/uploadcheck";
const excelBox = ref(false);
const uploadBtn = ref(false);
const uploadFile = ref("");
const fileName = ref("");

function excelBoxOpen() {
  excelBox.value = true;
}

function getfilepath(e: any) {
  const file = e.target.files[0];
  fileName.value = file.name;
  uploadFile.value = file;
  uploadBtn.value = false;
}

function upload() {
  if (!uploadFile.value) {
    ElMessage({
      type: "warning",
      message: "请选择文件！",
    });
    return;
  }

  let formdata = new FormData();
  formdata.append("file", uploadFile.value);
  let config = { headers: { "Content-Type": "multipart/form-data" } };
  request
    .post(uploadApi, formdata, config)
    .then((res) => {
      ElMessage({
        type: "success",
        message: "上传成功！",
      });

      excelBox.value = false;
      uploadBtn.value = true;
      search();
    })
    .catch((error) => {
      console.log(error);
    });
}

async function deleteItem(id: any) {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const { data } = await request({
      url: `/mes/mesinitialinventorymaintenance/deleteItem/${id}`,
      method: "post",
    });
    ElMessage.success("删除成功！");
    search();
  });
}
// 导入计划
const inventoryImportRef = ref();
const uploadErrorRef = ref();
const errorDataList = ref([]);
async function inventoryImportApiFunc(formdata: FormData, config: any) {
  await request
    .post(uploadApi, formdata, config)
    .then((res: any) => {
      inventoryImportRef.value.resCode = 0;
      if (res.code === 200 && Array.isArray(res.data) && res.data.length > 0) {
        // 弹出提示框提醒是否继续导入
        ElMessageBox.confirm("数据存在重复，是否继续导入?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
          closeOnClickModal: false,
        }).then(() => {
          // 导入接口
          save(res.data);
        });
      } else {
        ElMessage.success("导入成功！");
      }
    })
    .catch((e) => {
      inventoryImportRef.value.resCode = 500;
    });
}
const inventoryImport = () => {
  let params = {
    title: "导入初期库存",
    tempApi: "", //模板下载
    importApi: inventoryImportApiFunc, // 导入
    getTableList: getTableList, // 成功后回调
    isShowTemp: false,
    otherParams: {},
  };
  inventoryImportRef.value.acceptParams(params);
};
async function save(list) {
  await request({
    url: `/mes/mesinitialinventorymaintenance/uploadExcel`,
    method: "post",
    data: list,
  });
  ElMessage.success("导入成功！");
  search();
}
//产品选择
const showWorkOrderSelect = () => {
  selectDialogSELECT.value.visible = true;
};
//选择物料弹窗
const selectDialogSELECT = ref({
  visible: false,
});
const changeVisibleSELECT = (val: boolean, data: any) => {
  selectDialogSELECT.value.visible = val;
  if (data) {
    searchParam.value.materialId = data.id;
    searchParam.value.materialCode = data.materialCode;
  }
};
// 回显的数据
const brekList = ref([]);
const resetMaterial = () => {
  searchParam.value.materialId = "";
  searchParam.value.materialCode = "";
};
</script>
